﻿using HimVoiceStudio.Audio;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HimVoiceStudio
{
    public class AudioPlayer : IDisposable
    {
        private WaveOut _out;
        public event EventHandler OnStop;
        public event EventHandler<SampleReceivedEventArgs> OnSample;
        private ISampleProvider _sampleProvider;
        public AudioPlayer(ISampleProvider provider) {
            _out = new WaveOut();
            DisposableSampleNotifier notifier = new DisposableSampleNotifier(provider);
            notifier.OnSample += Notifier_OnSample;
            _sampleProvider = notifier;
            _out.PlaybackStopped += _out_PlaybackStopped;
            _out.DesiredLatency = 80;
            _out.Init(notifier);
        }

        private void Notifier_OnSample(object sender, SampleReceivedEventArgs e)
        {
            OnSample?.Invoke(this, e);
        }

        public AudioPlayer(IWaveProvider provider): this(new DisposableWaveToSampleProvider(provider))
        {
            // just do nothing here. 
        }

        public void Play()
        {
            _out.Play();
        }

        private void _out_PlaybackStopped(object sender, StoppedEventArgs e)
        {
            OnStop?.Invoke(this, EventArgs.Empty);
        }

        public void Stop()
        {
            _out.PlaybackStopped -= _out_PlaybackStopped;
            _out.Stop();
            OnStop?.Invoke(this, EventArgs.Empty);
        }

        public void Dispose()
        {
            _out.PlaybackStopped -= _out_PlaybackStopped;
            _out?.Stop();
            if(_sampleProvider is IDisposable disposable)
            {
                disposable?.Dispose();
            }
        }
    }
}
